#pragma once

#include <string>
#include <unistd.h>
#include <iostream>
#include <cstdlib>
#include <cstring>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "log.hpp"

namespace Client
{

    const int BUFFER_SIZE = 1024;

    enum
    {
        USAGE_ERROR = 1,
        SOCKET_ERROR,
        CONNECT_ERROR
    };

    class TcpClient
    {
    public:
        TcpClient(const std::string& ServerIp, const uint16_t& ServerPort)
            : _sockfd(-1), _ServerPort(ServerPort), _ServerIp(ServerIp)
        {}

        ~TcpClient()
        {
            if (_sockfd >= 0)
                close(_sockfd);
        }

        void init()
        {
            _sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                std::cerr << "socket error" << std::endl;
                exit(SOCKET_ERROR);
            }
        }

        void start()
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = inet_addr(_ServerIp.c_str());
            server.sin_port = htons(_ServerPort);
            if (connect(_sockfd, (const sockaddr*)&server, sizeof(server)) != 0)
            {
                std::cerr << "connect error" << std::endl;
                exit(CONNECT_ERROR);
            }
            else
            {
                std::string mesg;
                char buffer[BUFFER_SIZE] = "";
                while (true)
                {
                    std::cout << "请输入>: ";
                    std::getline(std::cin, mesg);
                    write(_sockfd, mesg.c_str(), mesg.size());

                    int n = read(_sockfd, buffer, sizeof(buffer)-1);
                    if (n > 0)
                    {
                        buffer[n] = 0;
                        std::cout << "server回复 # " << buffer << std::endl;
                    }
                    else 
                    {
                        break;
                    }
                }
            }
        }

        bool is_connect()
        {
            //
        }

    private:
        int _sockfd;
        uint16_t _ServerPort;
        std::string _ServerIp;

    };
}